<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j con-box uc-order page-uc-order">
    <!-- 导航 -->
    <div class="uc-nav">
      <div class="nav-box">
        <div
          :class="['nav-item', status === 0 ? 'active' : '']"
          @click="changeStatus(0)"
        >
          <span class="text">{{ $t('ucOrder.allOrders') }}</span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', status === 1 ? 'active' : '']"
          @click="changeStatus(1)"
        >
          <span class="text">
            {{ $t('obligation') }}
            <em class="number">{{ orderCountData.unPay }}</em>
          </span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', status === 2 ? 'active' : '']"
          @click="changeStatus(2)"
        >
          <span class="text">
            {{ $t('pendingDelivery') }}
            <em class="number">{{ orderCountData.payed }}</em>
          </span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', status === 3 ? 'active' : '']"
          @click="changeStatus(3)"
        >
          <span class="text">
            {{ $t('pendingReceipt') }}
            <em class="number">{{ orderCountData.consignment }}</em>
          </span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', status === 5 ? 'active' : '']"
          @click="changeStatus(5)"
        >
          <span class="text">
            {{ $t('completed') }}
            <em class="number">{{ orderCountData.success }}</em>
          </span>
          <i class="line" />
        </div>
      </div>
    </div>
    <!-- /导航 -->
    <!-- 搜索 -->
    <div class="uc-serach">
      <div class="left">
        <div class="select-item">
          <span class="tit">{{
            [
              $t('ucOrder.allOrders'),
              $t('ucOrder.lastSevenDays'),
              $t('ucOrder.lastThreeMonths'),
              $t('ucOrder.threeMonthsAgo'),
            ][orderTimeStatus]
          }}</span>
          <div class="select">
            <span
              class="s-item"
              @click="changeOrderTime(0)"
            >{{
              $t('ucOrder.allOrders')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderTime(1)"
            >{{
              $t('ucOrder.lastSevenDays')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderTime(2)"
            >{{
              $t('ucOrder.lastThreeMonths')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderTime(3)"
            >{{
              $t('ucOrder.threeMonthsAgo')
            }}</span>
          </div>
        </div>
        <div class="select-item">
          <span class="tit">{{
            orderType >= 0
              ? [
                $t('ucOrder.generalOrders'),
                $t('ucOrder.groupingOrders'),
                $t('ucOrder.secondOrders'),
                $t('ucOrder.pointsOrders'),
              ][orderType]
              : $t('ucOrder.allOrders')
          }}</span>
          <div class="select">
            <span
              class="s-item"
              @click="changeOrderType(-1)"
            >{{
              $t('ucOrder.allOrders')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderType(0)"
            >{{
              $t('ucOrder.generalOrders')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderType(1)"
            >{{
              $t('ucOrder.groupingOrders')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderType(2)"
            >{{
              $t('ucOrder.secondOrders')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderType(3)"
            >{{
              $t('ucOrder.pointsOrders')
            }}</span>
          </div>
        </div>
        <div class="select-item">
          <span
            v-if="orderMold === 0 || orderMold === 1"
            class="tit"
          >{{
            [$t('ucOrder.physicalGoods'),$t('ucOrder.virtualGoods')][orderMold]
          }}</span>
          <span
            v-else
            class="tit"
          >{{ $t('ucOrder.allOrders') }}</span>
          <div class="select">
            <span
              class="s-item"
              @click="changeOrderMold(-1)"
            >{{
              $t('ucOrder.allOrders')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderMold(0)"
            >{{
              $t('ucOrder.physicalGoods')
            }}</span>
            <span
              class="s-item"
              @click="changeOrderMold(1)"
            >{{
              $t('ucOrder.virtualGoods')
            }}</span>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="search-value">
          <div
            class="ordernum"
            @click="showOptions()"
          >
            {{
              type === 0 ? $t('ucOrder.orderNumber') : $t('ucOrder.productName')
            }}
          </div>
          <div
            v-if="showOptionsBox"
            class="options"
          >
            <p
              v-if="type === 1"
              class="options-item"
              @click="selectSearchValue(0)"
            >
              {{ $t('ucOrder.orderNumber') }}
            </p>
            <p
              v-if="type === 0"
              class="options-item"
              @click="selectSearchValue(1)"
            >
              {{ $t('ucOrder.productName') }}
            </p>
          </div>
        </div>
        <div class="search-int">
          <input
            v-if="type === 0"
            v-model="orderNumber"
            type="text"
            class="input"
            :placeholder="$t('ucOrder.enterNumberpSearch')"
            @keyup.enter="searchOrder(1,true)"
          >
          <input
            v-if="type === 1"
            v-model="orderName"
            type="text"
            class="input"
            :placeholder="$t('ucOrder.enterProductSearch')"
            @keyup.enter="searchOrder(1,true)"
          >
        </div>
        <a
          href="javascript:void(0)"
          class="search"
          @click="searchOrder(1,true)"
        >{{
          $t('ucOrder.checkOrder')
        }}</a>
      </div>
    </div>
    <!-- /搜索 -->
    <!-- 订单列表 -->
    <div
      v-if="orderList.length"
      class="order-list"
    >
      <div class="order-table">
        <table
          style="border-spacing: 0"
          class="box"
        >
          <tbody>
            <tr class="box-tit">
              <th>{{ $t('products') }}</th>
              <th style="width: 110px">
                {{ $t('quantity') }}
              </th>
              <th
                style="width: 120px"
                class="pr"
              >
                {{ $t('priceOne') }}
              </th>
              <th style="width: 130px">
                {{ $t('totalAll') }}
              </th>
              <th style="width: 130px">
                {{ $t('status') }}
              </th>
              <th style="width: 130px">
                {{ $t('operation') }}
              </th>
            </tr>
          </tbody>
          <tbody
            v-for="(order, index) in orderList"
            :key="index"
          >
            <tr class="box-space">
              <td colspan="6" />
            </tr>
            <tr class="box-hd">
              <td colspan="6">
                <div class="time">
                  {{ order.createTime }}
                </div>
                <div class="order-number">
                  {{ $t('orderNumberT') }}：
                  <span class="num">{{ order.orderNumber }}</span>
                </div>
                <!-- 图标有了但没有文字显示 -->
                <div
                  class="shop"
                  style="margin-left: 140px"
                  @click="toShop(order.shopId)"
                >
                  <span class="shop-icon" />
                  {{ order.shopName }}
                  <span v-if="order.shopName == null">{{ $t('ucOrder.officialSelf') }}</span>
                </div>
                <!-- 跳转客服 -->
                <span
                  class="btn-im"
                  @click.stop="toChat(order.orderType !== 3 ? order.shopId : null,order.shopName,order.orderNumber)"
                />
                <div
                  v-if="order.status >= 5 && order.status !== 7"
                  class="del"
                  @click="showDelPop(order.orderNumber)"
                />
              </td>
            </tr>
            <tr
              v-for="(orderItem, orderItemIndex) in order.orderItemDtos"
              :key="orderItemIndex"
              class="box-tr"
            >
              <td>
                <div class="goods-info">
                  <div
                    class="img"
                    @click="toProdDetail(order.orderType, orderItem.prodId, order.seckillId,order.userScore)"
                  >
                    <img
                      v-if="orderItem.pic"
                      :src="checkFileUrl(orderItem.pic)"
                      alt
                      @error="handlePicError"
                    >
                    <img
                      v-else
                      src="@/assets/img/def.png"
                      alt
                    >
                  </div>
                  <div class="name-sku">
                    <div
                      class="name"
                      @click="toProdDetail(order.orderType, orderItem.prodId, order.seckillId,order.userScore)"
                    >
                      {{ orderItem.prodName }}
                    </div>
                    <div class="sku-info-con">
                      <span
                        v-if="orderItem.skuName"
                        class="sku"
                      >{{ orderItem.skuName }}</span>
                      <span
                        v-if="orderItem.giveawayOrderItemId"
                        class="order-sgin prod-sgin"
                      >{{ $t('prodDetail.gift') }}</span>
                    </div>

                    <div
                      v-if="orderItem.preSellTime"
                      class="sku-info-con"
                    >
                      <span class="sku">{{ formatDate(orderItem.preSellTime) }}&nbsp;{{ $t('prodDetail.startShipping') }}</span>
                    </div>

                    <div class="sku-info-con">
                      <span
                        v-if="order.orderType && orderItemIndex === 0"
                        class="order-sgin"
                      >{{ ['',$t('ucOrder.groupingOrders'),$t('ucOrder.secondOrders'),$t('ucOrder.pointsOrders')][order.orderType] }}</span>
                    </div>
                  </div>
                </div>
                <div class="gift-group">
                  <div
                    v-for="(orderGift, giftIndex) in orderItem.giveawayList"
                    :key="giftIndex"
                    class="gift-item"
                  >
                    <div class="giveaway-item-name">
                      【{{ $t('prodDetail.gift') }}】 {{ orderGift.prodName }}
                    </div>
                    <div class="giveaway-item-sku-count">
                      {{ orderGift.skuName || '' }} x{{ orderGift.prodCount }}
                    </div>
                  </div>
                </div>
              </td>
              <td>
                <div class="goods-number">
                  ×{{ orderItem.prodCount }}
                </div>
              </td>
              <td class="pr">
                <div class="amount">
                  <div class="price">
                    <span v-if="orderItem.price">￥{{ parsePrice(orderItem.price)[0] }}.{{
                      parsePrice(orderItem.price)[1]
                    }}</span>
                  </div>
                </div>
              </td>
              <td
                v-if="orderItemIndex === 0"
                :rowspan="order.orderItemDtos.length"
                class="bl"
              >
                <div class="amount">
                  <div class="price">
                    <span v-if="order.actualTotal">￥{{ parsePrice(order.actualTotal)[0] }}.{{
                      parsePrice(order.actualTotal)[1]
                    }}</span>
                    <span v-if="order.actualTotal && order.userScore">+</span>
                    <span v-if="order.userScore">{{ order.userScore }} {{ $t('ucOrder.points') }}</span>
                  </div>
                  <span v-if="order.status>1 && order.payType">
                    {{ [$t('payment.pointPay'),$t('payment.wechatPay'),$t('payment.aliPay'),$t('payment.wechatPay'),$t('payment.wechatPay'),$t('payment.wechatPay'),$t('payment.aliPay'),$t('payment.aliPay'),$t('payment.wechatPay'),$t('payment.balancePay')][order.payType] }}
                  </span>
                </div>
              </td>
              <td
                v-if="orderItemIndex === 0"
                :rowspan="order.orderItemDtos.length"
                class="bl"
              >
                <div class="status">
                  <div
                    :class="[
                      'text',
                      order.status > 4 && order.status !== 7 ? '' : 'no-finish',
                    ]"
                  >
                    {{
                      [
                        '',
                        $t('obligation'),
                        $t('pendingDelivery'),
                        $t('pendingReceipt'),
                        $t('pendinEvaluation'),
                        $t('completed'),
                        $t('canceled'),
                        $t('grouping'),
                      ][order.status]
                    }}
                    <text v-if="order.refundStatus === 1">
                      ({{ $t('memberCenter.refunding') }})
                    </text>
                  </div>
                  <a
                    href="javascript:void(0);"
                    class="order-detail"
                    style="background: #ffffff"
                    @click="toOrderDetail(order.orderNumber)"
                  >{{ $t('ucOrder.orderDetails') }}</a>
                </div>
              </td>
              <td
                v-if="orderItemIndex === 0"
                :rowspan="order.orderItemDtos.length"
                class="bl"
              >
                <div class="action">
                  <a
                    v-if="
                      order.status !== 2 &&
                        order.status !== 4 &&
                        order.status !== 7
                    "
                    href="javascript:void(0);"
                    :class="[
                      'action-btn',
                      order.status > 4 ? 'default' : 'active',
                    ]"
                    @click="orderOperation(order)"
                  >{{
                    [
                      '',
                      $t('ucOrder.payNow'),
                      $t('ucOrder.remindSellers'),
                      $t('ucOrder.confirmReceipt'),
                      '',
                      $t('ucOrder.buyAgain'),
                      $t('buyNow'),
                    ][order.status]
                  }}</a>
                  <a
                    v-if="order.shopId !== null && order.orderType !== 3"
                    href="javascript:void(0);"
                    class="action-a"
                    @click="operator(order.status, order.orderNumber)"
                  >{{ $t('ucOrder.addFavorites') }}</a>
                  <p />
                  <a
                    v-if="((order.orderInvoiceId && order.status !== 6) || (order.orderInvoiceId && (order.status === 6 && order.refundStatus))) && order.orderType !== 3 && (!order.returnMoneySts || order.returnMoneySts >= 6 || order.returnMoneySts === -1)"
                    href="javascript:void(0);"
                    class="action-a"
                    @click="toInvoice(order.orderInvoiceId,order.orderNumber)"
                  >{{ $t('invoice.viewInvoice') }}</a>
                  <a
                    v-if="!order.orderInvoiceId && (order.status !== 6 && order.status !== 1) && order.orderType !== 3 && (!order.returnMoneySts || order.returnMoneySts >= 6 || order.returnMoneySts === -1) && order.actualTotal"
                    href="javascript:void(0);"
                    class="action-a"
                    @click="showAddOrUpdateDialog(order.orderNumber,order.shopId)"
                  >{{ $t('invoice.InvoicingRequest') }}</a>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 提示弹窗 -->
      <div
        v-if="showTips"
        class="popup-mask"
      />
      <div
        v-if="showTips"
        class="popup-box"
      >
        <div class="tit">
          <div class="text">
            {{ $t('ucOrder.tips') }}
          </div>
          <div
            class="close"
            @click="showTips = 0"
          />
        </div>
        <div class="con">
          <div class="tip">
            <div class="tip-icon warning" />
            <div class="tip-info">
              <div
                v-if="showTips === 3"
                class="result"
              >
                {{ $t('ucOrder.sureReceivedGoods') }}
              </div>
              <div
                v-if="showTips === 3"
                class="date"
              >
                {{ $t('ucOrder.considerCarefully') }}
              </div>
              <div
                v-if="showTips === 6"
                class="result"
              >
                {{ $t('ucOrder.deleteTheOrder') }}
              </div>
              <div
                v-if="showTips === 6"
                class="date"
              >
                {{ $t('ucOrder.ordersNotRecovered') }}
              </div>
              <div class="btns">
                <a
                  v-if="showTips === 3"
                  href="javascript:void(0);"
                  class="btn-r"
                  @click="confirmReceive"
                >{{ $t('ucOrder.confirmReceipt') }}</a>
                <a
                  v-if="showTips === 6"
                  href="javascript:void(0);"
                  class="btn-r"
                  @click="delOrder"
                >{{ $t('delete') }}</a>
                <a
                  href="javascript:void(0);"
                  class="btn-g"
                  @click="cancelOpera"
                >{{ $t('cancel') }}</a>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 页码 -->
      <pagination
        v-model="current"
        :pages="pages"
        :current="current"
        :size="size"
        @change-page="getSearchProdPage(current)"
      />
      <!-- /页码 -->
    </div>
    <!-- /订单列表 -->
    <!-- 空列表提示 -->
    <empty-all-tips
      v-if="isEmpty"
      :text="$t('ucOrder.nanOrderYet')"
      :back="$t('ucOrder.goShopping')"
      :src-type="1"
    />
    <!-- /空列表提示 -->
    <add-or-edit-invoice
      v-if="showInvoiceAdd"
      ref="invoiceAddOrUpdateRef"
      @update-data="refreshChange"
      @hide-pop="hidePop"
    />
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import * as util from '@/utils/index.js'
import { ElMessage } from 'element-plus'
import defPng from '@/assets/img/def.png'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const formatDate = (val) => {
  if (val) {
    return util.tsToDate(val.replace(/-/g, '/'), 'Y-M-D')
  }
}

const delOrderNumber = ref('') // 要删除的订单号
const type = ref(0) // 查询类型  0-订单编号 1-商品名称

const status = ref(0)
const orderNumber = ref(null)
const orderName = ref(null)
watch(() => status.value, () => {
  orderName.value = ''
  orderNumber.value = ''
})

const orderType = ref(-1) // 订单类型筛选
watch(() => orderType.value, () => {
  orderName.value = ''
  orderNumber.value = ''
})

const current = ref(1) // 当前页
onMounted(() => {
  status.value = Number(route.query.status) || 0

  // 设置网页标题
  document.title = $t('userCenter.myOrders')
  current.value = 1
  getUserInfo() // 获取订单数量
  getOrderList() // 获取订单列表
})

/**
 * 跳转商品详情
 */
const toProdDetail = (orderType, prodId, seckillId, scoreFee) => {
  if (orderType === 2 && !seckillId) {
    ElMessage.warning($t('spike.currentSecondsAreOver'))
    return
  }
  const query = orderType === 3 ? { prodId, scoreFee } : { prodId }
  const newPage = router.resolve({ path: '/detail', query })
  let userId = null
  if (Cookie.get('bbcToken')) {
    userId = userStore.userId
  }
  http.get('/prod/prodInfo', {
    params: {
      prodId,
      userId
    }
  }).then(() => {
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  })
}

// 发票弹窗
const showInvoiceAdd = ref(false)
const invoiceAddOrUpdateRef = ref(null)
const showAddOrUpdateDialog = (orderId, shopId) => {
  showInvoiceAdd.value = true
  nextTick(() => {
    invoiceAddOrUpdateRef.value?.init(1, '', orderId, shopId)
  })
}

/**
 * 刷新回调
 */
const refreshChange = (visible) => {
  showInvoiceAdd.value = visible
  getOrderList()
}

const hidePop = (visible) => {
  showInvoiceAdd.value = visible
}

/**
 * 跳转客服
 */
// eslint-disable-next-line no-unused-vars
const toChat = (shopId, shopName, orderNumber) => {
  const shoppId = shopId || 1
  let routeUrl
  if (shopId == null) {
    routeUrl = router.resolve({
      path: '/chat',
      query: {
        shopId: shoppId,
        chatType: 1,
        orderNumber
      }
    })
  } else {
    routeUrl = router.resolve({
      path: '/chat',
      query: {
        shopId: shoppId,
        orderNumber
      }
    })
  }
  window.open(routeUrl.href, 'view_window')
}

/**
 * 跳转店铺页
 */
const toShop = (shopId) => {
  if (shopId) {
    router.push({
      path: '/shop-index',
      query: {
        sid: shopId
      }
    })
  } else {
    router.push({
      path: 'uc-integral',
      query: {
        sts: 1
      }
    })
  }
}

const orderTimeStatus = ref(0) // 订单时间筛选
/**
 * 切换订单状态
 * staus 0 = 全部 1 = 待支付 2 = 待发货 3 = 待收货  5 = 已完成
 */
const changeStatus = (statusPar) => {
  status.value = statusPar
  current.value = 1
  orderTimeStatus.value = 0
  orderType.value = -1
  getOrderList()
  getUserInfo()
}

const orderCountData = ref({})
/**
 * 获取订单数量
 */
const getUserInfo = () => {
  http.get('/p/user/centerInfo').then(({ data }) => {
    orderCountData.value = data.orderCountData
  })
}

const pages = ref(1) // 总页数
const size = ref(5)
const orderMold = ref(-1)
const orderList = ref([])
const isEmpty = ref(false)
/**
 * 获取订单列表
 */
const getOrderList = () => {
  isEmpty.value = false
  const params = {
    current: current.value,
    size: size.value,
    status: status.value,
    orderName: '',
    orderTimeStatus: orderTimeStatus.value || '',
    orderType: orderType.value >= 0 ? orderType.value : '',
    orderNumber: '',
    orderMold: orderMold.value
  }
  http
    .get('/p/myOrder/myOrderSearch', { params })
    .then(({ data }) => {
      data.records.forEach((order) => {
        order.useScoreTotal = 0
        order.orderItemDtos.forEach((orderItem) => {
          if (orderItem.useScore) {
            order.useScoreTotal += orderItem.useScore
          }
        })
      })
      orderList.value = data.records
      isEmpty.value = !orderList.value.length
      pages.value = data.pages
      scrollTo(0, 0)
    })
}

/**
 * 分页
 */
const getSearchProdPage = () => {
  searchOrder()
}

const showOptionsBox = ref(false) // 是否显示查询选项
/**
 * 显示选项框
 */
const showOptions = () => {
  showOptionsBox.value = !showOptionsBox.value
}

/**
 * 获取查询类型
 */
const selectSearchValue = (typePar) => {
  type.value = typePar
  showOptionsBox.value = false
  orderName.value = ''
  orderNumber.value = ''
}

const handlePicError = (e) => {
  e.target.src = defPng
}

let theData = null // 保存上次点击查询的请求条件
/**
 * 根据订单编号/商品名称 搜索订单
 */
const searchOrder = (query, newData = false) => {
  isEmpty.value = false
  if (query) {
    current.value = 1
  }
  if (newData || !theData) {
    theData = {
      status: status.value,
      orderNumber: orderNumber.value || '',
      orderName: orderName.value || '',
      orderTimeStatus: orderTimeStatus.value,
      orderType: orderType.value >= 0 ? orderType.value : '',
      current: query ? 1 : current.value,
      size: size.value,
      orderMold: orderMold.value
    }
  } else {
    theData.current = query ? 1 : current.value
    theData.size = size.value
  }
  http
    .get('/p/myOrder/myOrderSearch', {
      params: theData
    })
    .then(({ data }) => {
      orderList.value = data.records
      isEmpty.value = !orderList.value.length
      pages.value = data.pages
      if (current.value !== undefined) {
        localStorage.setItem('bbcOrderList', JSON.stringify(orderList.value))
        localStorage.setItem('bbcCurrent', JSON.stringify(current.value))
      }
    })
}

/**
 * 跳转订单详情
 */
const toOrderDetail = (orderNumber) => {
  router.push({
    path: '/order-detail',
    query: { orderNumber }
  })
}

const showTips = ref(0)
let currentOrderNumber = null
/***
 *  获取用户交易单号
 * @param {String} orderNumber 订单编号
 */
const getTransactionId = (orderNumber) => {
  return new Promise(resolve => {
    http.get(`/p/myOrder/checkTradeManaged/${orderNumber}`).then(({ data }) => {
      // data.orderStatus 订单状态枚举:(1)待发货，(2) 已发货，(3)确认收货;(4)交易完成(5) 已退款
      // data.bizPayNo 支付单号
      // 接口返回订单号且状态为(2) 已发货时，需要在小程序端确认收货，否则可以正常收货
      if (data.bizPayNo && data.orderStatus === 2) {
        resolve(data.bizPayNo)
      } else {
        resolve(false)
      }
    })
  })
}
/**
 * 订单操作
 */
const orderOperation = async (order) => {
  // status: 1立即付款 3确认收货  5再次购买 6立即购买
  const { status, orderNumber, actualTotal, orderType } = order
  if (status === 1) {
    sessionStorage.setItem('bbcPay_total', actualTotal)
    sessionStorage.setItem('bbcPay_orderNumber', orderNumber)
    JSON.parse(localStorage.getItem('bbcPaySwitchInfo')) === null ? util.getSysPaySwitch(true, toPayMent) : toPayMent()
  }
  if (status === 3) {
    const transactionId = await getTransactionId(orderNumber)
    if (transactionId) {
      return ElMessage({
        message: $t('ucOrder.mpRceiptTips'),
        type: 'warning'
      })
    }

    // 确认收货提醒
    showTips.value = 3
    currentOrderNumber = orderNumber
  }
  if (status === 5) {
    if (order.orderMold === 1) {
      const newPage = router.resolve({ path: '/detail', query: { prodId: order.orderItemDtos[0].prodId } })
      window.open(newPage.href, '_blank', 'noopener,noreferrer')
      return
    }
    let prodList = []
    let prodId = null
    let scoreFee = 0

    if (orderType === 3) {
      orderList.value.forEach((el) => {
        if (el.orderNumber === orderNumber) {
          scoreFee = el.orderItemDtos[0].useScore
          prodId = el.orderItemDtos[0].prodId
        }
      })
      const newPage = router.resolve({ path: '/detail', query: { prodId, scoreFee } })
      window.open(newPage.href, '_blank', 'noopener,noreferrer')
      return
    }
    orderList.value.forEach((el) => {
      if (el.orderNumber === orderNumber) {
        prodList = el.orderItemDtos
        addCart(prodList, el.shopId, el.shopName)
      }
    })
  }
  if (status === 6) {
    let prodId = 0
    let scoreFee = 0
    orderList.value.forEach((el) => {
      if (el.orderNumber === orderNumber) {
        prodId = el.orderItemDtos[0].prodId
        scoreFee = el.orderItemDtos[0].useScore
      }
    })
    let newPage
    if (orderType === 3) {
      newPage = router.resolve({ path: '/detail', query: { prodId, scoreFee } })
    } else {
      newPage = router.resolve({ path: '/detail', query: { prodId } })
    }
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  }
}

/**
 * 到支付页面
 */
const toPayMent = () => {
  router.push({ path: '/payment' })
}

/**
 * 批量加入购物车
 */
const addCart = async (prodList, shopId, shopName) => {
  try {
    for (let i = 0; i < prodList.length; i++) {
      await addToCart(prodList[i], shopId, shopName)
    }
    ElMessage.success(
      $t('success') + $t('prodDetail.addToCart')
    )
  } catch (error) {}
  await router.push({ path: '/cart' })
}

/**
 * 加入购物车
 */
const addToCart = (prod, shopId, shopName) => {
  return http.post('/p/shopCart/changeItem', {
    basketId: 0,
    count: prod.prodCount,
    prodId: prod.prodId,
    shopId,
    shopName,
    skuId: prod.skuId
  }).then(() => {
    getCartCount()
  })
}

const cartNumberStore = useCartNumberStore()
/**
 * 获取购物车商品总数
 */
const getCartCount = () => {
  http.get('/p/shopCart/prodCount').then(({ data }) => {
    cartNumberStore.changeCartNumber(data)
  })
}

/**
 * 订单确认收货
 */
const confirmReceive = () => {
  showTips.value = 0
  http.put('/p/myOrder/receipt/' + currentOrderNumber)
    .then(() => {
      ElMessage({
        message: $t('ucOrder.confirmReceiptSuccessfully'),
        type: 'success',
        duration: 1000
      })
      if (orderList.value.length === 1 && current.value > 1) {
        current.value--
      }
      getOrderList()
      getUserInfo()
    })
}

// eslint-disable-next-line no-unused-vars
const operator = (status, orderNumber) => {
  // 添加收藏
  const prodIds = []
  orderList.value.forEach((el) => {
    if (el.orderNumber === orderNumber) {
      el.orderItemDtos.forEach((prodItem) => {
        prodIds.push(prodItem.prodId)
      })
    }
  })
  addFavProd(prodIds)
}

/**
 * 取消操作
 */
const cancelOpera = () => {
  showTips.value = 0
}

/**
 * 添加收藏
 */
const addFavProd = (prodIds) => {
  // 相同id去重
  const prodIdStr = Array.from(new Set(prodIds)).toString()
  // 查询商品是否已收藏
  if (!Cookie.get('bbcToken')) {
    return
  }
  http
    .get('/p/user/collection/isCollection', {
      params: {
        prodId: prodIdStr
      }
    })
    .then(({ data }) => {
      if (data) {
        ElMessage({
          message: $t('ucOrder.collected'),
          type: 'success',
          duration: 1000
        })
      } else {
        http
          .post('/p/user/collection/orderProdCollectionAll', prodIdStr)
          .then(() => {
            ElMessage({
              message: $t('ucOrder.productCollectionSuccess'),
              type: 'success',
              duration: 1000
            })
          })
      }
    })
}

/**
 * 删除确认弹窗
 */
const showDelPop = (orderNumber) => {
  showTips.value = 6
  delOrderNumber.value = orderNumber
}

/**
 * 删除订单
 */
const delOrder = () => {
  http
    .delete('/p/myOrder/' + delOrderNumber.value)
    .then(({ data }) => {
      showTips.value = 0
      ElMessage({
        type: 'success',
        duration: 1000,
        message: data
      })
      if (orderList.value.length === 1 && current.value > 1) {
        current.value--
      }
      getOrderList()
      getUserInfo()
    })
}

/**
 * 切换订单时间
 */
const changeOrderTime = (orderTimeStatusPar) => {
  orderName.value = ''
  orderNumber.value = ''
  orderTimeStatus.value = orderTimeStatusPar
  current.value = 1
  searchOrder(1, true)
}

/**
 * 切换订单类型
 */
const changeOrderType = (orderTypePar) => {
  orderName.value = ''
  orderNumber.value = ''
  orderType.value = orderTypePar
  current.value = 1
  searchOrder(1, true)
}

/**
 * 切换订单类别
 */
const changeOrderMold = (orderMoldPar) => {
  orderMold.value = orderMoldPar
  current.value = 1
  searchOrder(1, true)
}

/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

/**
 * 查看发票
 */
const toInvoice = (orderInvoiceId, orderNumber) => {
  router.push({
    path: '/invoice-detail',
    query: {
      orderNumber,
      orderInvoiceId
    }
  })
}

</script>

<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
<style lang="scss" scoped>
@use "index";
</style>
